package cn.com.se.sharepictrue.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.se.sharepictrue.R;
import cn.com.se.sharepictrue.application.Data;
import cn.com.se.sharepictrue.bean.UserInfoBean;
import cn.com.se.sharepictrue.business.CallBack;
import cn.com.se.sharepictrue.business.ImageLoader;
import cn.com.se.sharepictrue.business.NetworkResponse;
import cn.com.se.sharepictrue.business.ShareApi;
import cn.com.se.sharepictrue.utils.ImageUtils;
import cn.com.se.sharepictrue.utils.StringUtils;
import cn.com.se.sharepictrue.utils.ToastUtils;
import cn.com.se.sharepictrue.widget.MyProgressDialog;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 个人信息界面
 * Created by KIDNG on 2015/11/6.
 */
public class MineInfoActivity extends ActionBarActivity {
    @Bind(R.id.tb_mine_info_title)
    Toolbar mTbMineInfoTitle;
    @Bind(R.id.tv_mine_info_user_count)
    TextView mUserPhone;
    @Bind(R.id.tv_mine_info_nickname)
    TextView mUserNickName;
    @Bind(R.id.tv_mine_info_introduction)
    TextView mUserIntroduction;
    @Bind(R.id.tv_mine_info_email)
    TextView mUserEmail;
    @Bind(R.id.tv_mine_info_sex)
    TextView mUserSex;
    //    @Bind(R.id.tv_mine_info_page)
//    TextView mUserHomePage;
    @Bind(R.id.tv_mine_info_qq)
    TextView mUserQQ;
    @Bind(R.id.civ_mine_info_avatar)
    CircleImageView mUserPic;
    @Bind(R.id.btn_mine_modify)
    Button mSaveModifyButton;

    private UserInfoBean userInfo;
    private EditText mEditText = null;
    private String mModityPortraitPath = "";
    private Uri mPortraitUri;
    private Bitmap bitmap;

    private final static int NICK_NAME = 1;
    private final static int INTRODUCTION = 2;
    //private final static int SEX = 3;
    private final static int QQ = 4;
    private final static int EMAIL = 5;
    private final static int HOMEPAGE = 6;

    private final static int GALLERY = 0;
    private final static int CUT = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_info);
        ButterKnife.bind(this);
        initToolBar();
        getUserInfo();
    }

    private void initToolBar() {
        setSupportActionBar(mTbMineInfoTitle);
        mTbMineInfoTitle.setTitleTextColor(Color.WHITE);
    }

    private void showAlertDialog(int type, TextView textView) {
        mEditText = new EditText(MineInfoActivity.this);
        mEditText.setSingleLine(INTRODUCTION != type);
        mEditText.setText(textView.getText());
        new AlertDialog.Builder(MineInfoActivity.this).setTitle("请输入:").setView(mEditText).setPositiveButton("确定", new OnDialogButtonClick(type)).setNegativeButton("取消", null).show();
    }

    private void showSexPicker() {
        new AlertDialog.Builder(MineInfoActivity.this).setTitle("请选择:").setPositiveButton("女", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                mUserSex.setText("女");
                mSaveModifyButton.setVisibility(View.VISIBLE);
            }
        }).setNegativeButton("男", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                mUserSex.setText("男");
                mSaveModifyButton.setVisibility(View.VISIBLE);
            }
        }).show();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:

                finishWithResult();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void getUserInfo() {
        userInfo = ((Data) getApplicationContext()).getUserInfo();
//        ToastUtils.show(this, userInfo.toString());
        setUserInfoData();

    }

    private void setUserInfoData() {
        mUserPhone.setText(userInfo.getUserPhone());
        mUserNickName.setText(userInfo.getUserName());
        mUserIntroduction.setText(userInfo.getSighature());
        mUserSex.setText(userInfo.getGender());
        mUserQQ.setText(userInfo.getQq());
        mUserEmail.setText(userInfo.getUserEmail());
        //mUserEmail.setText(userInfo.get);
        if (userInfo.getPortraitImage() != null)
            mUserPic.setImageBitmap(userInfo.getPortraitImage());
        else if (!StringUtils.isEmpty(userInfo.getPortrait()) && userInfo.getPortrait().length() > 26)
            ImageLoader.getInstance(MineInfoActivity.this).load(mUserPic, userInfo.getPortrait());
        else
            mUserPic.setImageResource(R.mipmap.bg_drawer);

    }

    private void selectPortraitFromGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, GALLERY);
    }

    private void corpPortrait(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1); // 裁剪后输出图片的尺寸大小
        mPortraitUri = Uri
                .parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "portrait.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mPortraitUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, CUT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == GALLERY) {
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                corpPortrait(uri);
            }
        } else if (requestCode == CUT) {
            try {
                bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(mPortraitUri));
                mUserPic.setImageBitmap(bitmap);
                mModityPortraitPath = ImageUtils.getRealFilePath(MineInfoActivity.this, mPortraitUri);
                mSaveModifyButton.setVisibility(View.VISIBLE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void saveInfoModify() {
        ShareApi.modifyUser(MineInfoActivity.this,
                mUserNickName.getText().toString(),
                mUserIntroduction.getText().toString(),
                mUserSex.getText().toString(),
                mUserQQ.getText().toString(),
                mUserEmail.getText().toString(),//                mUserHomePage.getText().toString(),
                mModityPortraitPath,
                new CallBack<NetworkResponse<String>>(this, "资料上传中") {

                    @Override
                    public void onFail() {
                        ToastUtils.show(MineInfoActivity.this, "网络出错了");
                    }

                    @Override
                    public void onResponse(NetworkResponse<String> response) {
                        if (!response.isStatus())
                            ToastUtils.show(MineInfoActivity.this, response.getError());
                        else {
                            ToastUtils.show(MineInfoActivity.this, "保存成功");
                            saveComplete();
                        }
                    }
                });
    }

    private void saveComplete() {
        mSaveModifyButton.setVisibility(View.GONE);
        //重新设置userInfo的数据
        //
        userInfo.setUserName(mUserNickName.getText().toString());
        userInfo.setSighature(mUserIntroduction.getText().toString());
        userInfo.setGender(mUserSex.getText().toString());
        userInfo.setPortraitImage(bitmap);
        userInfo.setUserEmail(mUserEmail.getText().toString());
        userInfo.setQq(mUserQQ.getText().toString());
    }

    @OnClick({R.id.ll_mine_info_nickname, R.id.ll_mine_info_introduction,
            R.id.ll_mine_info_sex, R.id.ll_mine_info_qq,
            R.id.ll_mine_info_email, R.id.civ_mine_info_avatar, R.id.btn_mine_modify})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_mine_info_nickname:
                showAlertDialog(NICK_NAME, mUserNickName);
                break;
            case R.id.ll_mine_info_introduction:
                showAlertDialog(INTRODUCTION, mUserIntroduction);
                break;
            case R.id.ll_mine_info_sex:
                //showAlertDialog(SEX, mUserSex);
                showSexPicker();
                break;
            case R.id.ll_mine_info_qq:
                showAlertDialog(QQ, mUserQQ);
                break;
            case R.id.ll_mine_info_email:
                showAlertDialog(EMAIL, mUserEmail);
                break;
            case R.id.civ_mine_info_avatar:
                selectPortraitFromGallery();
                break;
            case R.id.btn_mine_modify:
                saveInfoModify();
                break;
        }
    }

    private class OnDialogButtonClick implements DialogInterface.OnClickListener {

        private int type;

        public OnDialogButtonClick(int type) {
            this.type = type;
        }

        @Override
        public void onClick(DialogInterface dialog, int which) {
            mSaveModifyButton.setVisibility(View.VISIBLE);
            switch (type) {
                case NICK_NAME:
                    mUserNickName.setText(mEditText.getText());
                    break;
                case INTRODUCTION:
                    mUserIntroduction.setText(mEditText.getText());
                    break;
                //case SEX:
                    //mUserSex.setText(mEditText.getText());
                   // break;
                case QQ:
                    mUserQQ.setText(mEditText.getText());
                    break;
                case EMAIL:
                    mUserEmail.setText(mEditText.getText());
                    break;
//                case HOMEPAGE:
//                    mUserHomePage.setText(mEditText.getText());
//                    break;
                default:
                    break;
            }
            mEditText.setText(null);
            dialog.dismiss();
        }
    }

    private void finishWithResult() {
        MineInfoActivity.this.setResult(0);
        finish();
    }

    @Override
    public void onBackPressed() {
        finishWithResult();
        super.onBackPressed();
    }
}
